<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form-model ref="form" :model="openConfig" layout="vertical" class="rx-a-form-vertical">
                    <a-row>
                        <a-col :span="12">
                            <a-form-item  :label="i18n('targetFormSolution','目标表单方案')">
                                <rx-input-button style="width: calc(100% - 20px)" v-model="targetForm" @click="selectFormSolution"/>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="i18n('callback','回调方法')">
                                <a-input style="width: calc(100% - 20px)" v-model="openConfig.callback" :placeholder="i18n('callbackPlaceholder','在当前表单中编写方法，参数为')+'(action,data)'"></a-input>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-form-item :label="i18n('openMode','打开方式')">
                            <open-mode :local-config="openFormConfig"></open-mode>
                    </a-form-item>
                    <a-form-item  v-if="targetForm">
                        <a-button @click="add" type="primary"><a-icon type="plus"></a-icon> {{i18n('addTable','新增表映射')}}</a-button>
                        <div>
                            <a-collapse style="margin-top: 10px" default-active-key="0" :bordered="false">
                                <template #expandIcon="props">
                                    <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0"/>
                                </template>
                                <a-collapse-panel class="eventFuncDialog-panel" :header="i18n('reflection','映射')+(index+1)" :key="index" v-for="(item,index) in dataSource">
                                    <span slot="extra" @click.stop="">
                                        <div class="eventFuncDialog-extra">
                                            <div class="eventFuncDialog-file">
                                                <span>{{i18n('targetForm','目标表单')}}：</span>
                                                <div style="margin-left: 10px;flex: 1">
                                                    <a-select style="width: 200px;" v-model="item.targetTable" :options="targetTables" @change="targetChange(item,index)" :getPopupContainer="p=>p.parentNode"/>
                                                </div>
                                            </div>
                                            <my-icon class="delMethod" type="icontrash" @click="remove(index)"></my-icon>
                                        </div>
                                    </span>
                                    <div class="openFormConfig-grid">
                                        <div class="openFormConfig-grid-head" v-if="item.fieldConfig.length>0">
                                            <div>{{i18n("targetField","目标字段")}}</div>
                                            <div>{{i18n("bindType","映射类型")}}</div>
                                            <div>{{i18n("curTable","当前表")}}</div>
                                            <div>{{i18n("curField","当前字段")}}</div>
                                        </div>
                                        <div class="openFormConfig-grid-common" v-for="(obj,index1) in item.fieldConfig" :key="index1">
                                            <div class="openFormConfig-icon" @click="deleteField(index,index1)"><my-icon type="iconoffline"></my-icon></div>
                                            <div class="openFormConfig-select"> <a-select v-model="obj.targetField" :options="getFields(item.targetTable,targetBoEntity)" /></div>
                                            <div class="openFormConfig-select"><a-select v-model="obj.bindType" :options="bindTypes" /></div>
                                            <template v-if="obj.bindType=='fixed'">
                                                <div class="openFormConfig-fixed"><a-input v-model:value="obj.curField" style="width: 150px;" :placeholder="i18n('fixedPlaceholer','请填写固定值')"></a-input></div>
                                            </template>
                                            <template v-else-if="obj.bindType=='script'">
                                                <div class="openFormConfig-fixed"><a-input v-model:value="obj.curField" style="width: 150px;"  :placeholder="i18n('scriptPlaceholer','请填写表单方法名')" ></a-input></div>
                                            </template>
                                            <template v-else>
                                                <div class="openFormConfig-select"><a-select v-model="obj.curTable" :options="getCurTables(item)" @change="curTableChange(obj)"/></div>
                                                <div class="openFormConfig-select"><a-select :key="obj.curTable" v-model="obj.curField" :options="getFields(obj.curTable,curBoEntity)" /></div>
                                            </template>
                                        </div>
                                        <div style="height: 160px;display: flex;flex-direction: column;justify-items: center;align-items: center;" v-if="item.fieldConfig.length==0">
                                            <a-empty />
                                            <a-button size="large" style="margin-top: 10px;width: 100px" type="primary" @click="addField(item,index)">
                                               {{$ti18('rxList.add', '新增')}}
                                            </a-button>
                                        </div>
                                        <div v-if="item.fieldConfig.length>0" class="openFormConfig-add" @click="addField(item,index)"><my-icon type="iconaddition"></my-icon>{{$ti18('rxList.add', '新增')}}</div>
                                    </div>
                                </a-collapse-panel>
                            </a-collapse>
                        </div>
                    </a-form-item>
                </a-form-model>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import { RxDialog ,RxLayout ,Util} from "@lowcode/jpaas-common-lib";
import DialogBox from "@/assets/js/DialogBox";
import FormBoDefApi from "@/api/form/bo/formBoDef";
import OpenMode from "@/views/modules/form/core/listCommon/OpenMode";

export default {
    name: "openFormConfig",
    components:{
        OpenMode,
        RxDialog,
        RxLayout,
    },
    props:{
        layerid:{
            type:String
        },
        lydata:{
            type:Object
        },
        destroy:Function,
        config:{
            type:Object
        },
        curBoDefId:{
            type:String
        },

    },
    data() {
        return {
            columns: [
                {
                    title: this.i18n("targetField","目标字段"),
                    dataIndex: 'targetField',
                    width: 100,
                    scopedSlots: {customRender: 'targetField'}
                },
                {
                    title: this.i18n("curTable","当前表"),
                    dataIndex: 'curTable',
                    width: 100,
                    scopedSlots: {customRender: 'curTable'}
                },
                {
                    title: this.i18n("curField","当前字段"),
                    dataIndex: 'curField',
                    width: 100,
                    scopedSlots: {customRender: 'curField'}
                },
            ],
            openConfig:{
                formAlias:"",
                formName:"",
                boDefId:"",
                formConfig:"",
                callback:""
            },
            //当前表单
            curBoEntity:"",
            curTables:[],
            curFields:[],
            //目标表单
            targetForm:"",
            targetBoEntity:"",
            targetTables:[],
            dataSource:[],
            //打开表单大小配置
            openFormConfig: {
                pkId:"",
                formAlias: "",//表单方案alias
                formName:"",//表单方案名称
                boDefId:"",//boDefId
                mappingType:"",//数据映射
                boEntityAlias:"",//绑定控件
                boEntityName:"",//
                gridName:"main",//表名
                curtype:"main",//main""onetoone",
                //回调方法
                callbackMethod:'',
                //是否只读
                readonly:false,
                /*{
                    returnLabel: "FXK",
                    returnValue: "FXKLB",
                    returnField: "",
                    bindField: "user",
                    bindFieldLabel : "用户",
                    valmode: "single",
                    ctltype: "rx-user",
                    idx_: "nsprmsm786965"
                }*/
                returnFields:[],
                //窗口大小
                model:true,
                isMax:"YES",
                height:600,
                width:800

            },
            bindTypes:[{value:"field",label: this.i18n("field","字段")},
                {value:"fixed",label: this.i18n("fixed","固定值")},
                {value:"script",label: this.i18n("script","脚本")}
            ]
        }
    },
    created(){
        this.initConfig();
        this.getBoEntity(this.curBoDefId,"cur");


    },
    methods:{
        i18n(name,text,key){
            return this.$ti18(name,text,"openFormConfigLang",key);
        },
        initConfig(){
            if(this.config.openFormConfig){
                this.openFormConfig=Object.assign(this.openFormConfig,this.config.openFormConfig);
            }
            if(this.config.openConfig){
                this.openConfig=Object.assign(this.openConfig,this.config.openConfig);
            }
            if(this.openConfig.boDefId){
                this.getBoEntity(this.openConfig.boDefId,"select");
            }
            if(this.openConfig.formConfig){
                this.dataSource=JSON.parse(this.openConfig.formConfig);
            }
            if(this.openConfig.formAlias){
                this.targetForm = JSON.stringify({text:this.openConfig.formName,value:this.openConfig.formAlias});
            }
        },
        /**
         * 选择表单方案
         */
         selectFormSolution() {
            let confSol = {curVm: this, widthHeight: ['800px', '600px'], data: {multiSelect: false}};
            let self_ = this;
            DialogBox.openSoution(confSol, function (data) {
                self_.targetForm = JSON.stringify({text:data.name,value:data.alias});
                self_.openConfig.formAlias=data.alias;
                self_.openConfig.formName=data.name;
                self_.openConfig.boDefId=data.bodefId;
                self_.dataSource=[];
                self_.getBoEntity(self_.openConfig.boDefId,"select");
            })
        },
        getBoEntity(boDefId,type){
            let needCommon=type=="cur";
            FormBoDefApi.getByDefIdCommonField({boDefId:boDefId,needCommon:needCommon}).then(res=>{
                if(res.success){
                    if(type=="cur"){
                        this.curBoEntity= res.data.formBoEntity;
                        this.curTables= this.getTables(this.curBoEntity);
                    }else {
                        this.targetBoEntity= res.data.formBoEntity;
                        this.targetTables=this.getTables(this.targetBoEntity);
                    }
                }
            });
        },
        handleSubmit(){
            this.openConfig.formConfig=JSON.stringify(this.dataSource);
            var config = {
                openConfig:this.openConfig,//打开表单中的表单数据
                openFormConfig:this.openFormConfig//打开表单的大小配置数据
            }
            Util.closeWindow(this,'ok',config);
        },
        cancel(){
            Util.closeWindow(this);
        },
        add(){
            this.dataSource.push({
                targetTable:"",
                targetType:"",
                fieldConfig:[]
            })
        },
        remove(index){
            let self=this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                zIndex: 20000,
                content: this.$ti18("rxMsa.delCurrentInfo","您确定要删除当前项吗?"),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    self.dataSource.splice(index,1);
                },
                onCancel() {
                }
            })
        },
        addField(item, index) {
            if (!item.targetTable) {
                this.$message.warning(this.i18n("selectForm","请先选择目标表单"));
                return;
            }
            let curTable = "";
            let curType = "";
            if (this.dataSource[index].fieldConfig && this.dataSource[index].fieldConfig.length > 0) {
                curTable = this.dataSource[index].fieldConfig[this.dataSource[index].fieldConfig.length - 1].curTable;
                curType = this.dataSource[index].fieldConfig[this.dataSource[index].fieldConfig.length - 1].curType;
            }
            this.dataSource[index].fieldConfig.push({
                targetField: "",
                curTable: curTable,
                curField: "",
                bindType: "field",
                curType: curType
            })
        },
        removeField(index){
            this.$refs["table"+index][0].removeRows();
        },
        getTables(boEntity){
            let tables=[];
            if(boEntity){
                //主表
                tables.push({
                    value:boEntity.alias,
                    label:boEntity.name,
                    type: boEntity.boRelation.type
                })
                if(boEntity.boEntityList){
                    for (let i = 0; i < boEntity.boEntityList.length; i++) {
                        tables.push({
                            value:  boEntity.boEntityList[i].alias,
                            label:  boEntity.boEntityList[i].name,
                            type: boEntity.boEntityList[i].boRelation.type
                        })
                    }
                }
            }
            return tables;
        },
        getCurTables(record){
            let value=record.targetTable;
            let tables=[];
            let targetTable=this.targetTables.find(item=>{
                if(value==item.value){
                    return true;
                }
            });
            if(!targetTable){
                return  tables;
            }
            if(targetTable.type=="main" || targetTable.type=="onetoone"){
                this.curTables.map(item=>{
                    if(item.type=="main" || item.type=="onetoone"){
                        tables.push(item);
                    }
                });
            }else {
                //已有子表情况 不允许再选择其他的
                let tableFlag="";
                for (let i = 0; i < record.fieldConfig.length; i++) {
                    if(!record.fieldConfig[i].curTable){
                        continue;
                    }
                    let curTable=this.curTables.find(item=>{
                        if(record.fieldConfig[i].curTable==item.value && item.type=="onetomany"){
                            return true;
                        }
                    });
                    if(curTable){
                        tableFlag=curTable.value;
                        break;
                    }
                }
                this.curTables.map(item=>{
                    if(!tableFlag || item.type!="onetomany" || item.value==tableFlag ){
                        tables.push(item);
                    }
                });
            }
            return tables;
        },
        getFields(table,boEntity){
            let fields=[];
            if(!table){
                return fields;
            }
            if(boEntity.alias==table){
                for (let i = 0; i <  boEntity.boAttrList.length; i++) {
                    fields.push({
                        value:boEntity.boAttrList[i].name,
                        label:boEntity.boAttrList[i].comment,
                    })
                }
            }else {
                if(boEntity.boEntityList){
                    for (let i = 0; i < boEntity.boEntityList.length; i++) {
                        let obj=boEntity.boEntityList[i];
                        if(obj.alias==table){
                            for (let i = 0; i <  obj.boAttrList.length; i++) {
                                fields.push({
                                    value:obj.boAttrList[i].name,
                                    label:obj.boAttrList[i].comment,
                                })
                            }
                            break;
                        }
                    }
                }
            }
            return fields;
        },
        targetChange(item,index){
            item.curTable="";
            item.fieldConfig=[];
            for (let i = 0; i < this.dataSource.length; i++) {
                if(this.dataSource[i].targetTable==item.targetTable && i!=index){
                    item.targetTable="";
                    this.$message.warning(this.i18n("repeatTips","请勿重复选择!"));
                    return;
                }
            }
            let targetTable=this.targetTables.find(table=>{
                if(item.targetTable==table.value){
                    return true;
                }
            });
            item.targetType=targetTable.type;
        },
        curTableChange(record){
             this.$set(record,"curField","");
            let curTable=this.curTables.find(item=>{
                if(record.curTable==item.value){
                    return true;
                }
            });
            this.$set(record,"curType",curTable.type);
        },
        deleteField(index,index1){
            this.dataSource[index].fieldConfig.splice(index1,1)
        }
    }
}
</script>

<style lang="less">
.eventFuncDialog-panel{
    border-radius: 4px;
    background: white;
    border: solid 1px #dedede!important;
    margin-bottom: 16px;
    .ant-collapse-header{
    border-bottom: solid 1px #dedede;
    height: 50px;
    position: relative;
    padding: 14px 13px 14px 33px!important;
}
.ant-collapse-arrow{
    left: 13px!important;
}
}
.eventFuncDialog-extra{
    display: flex;
    align-content: center;
    height: 50px;
    width: calc(100% - 50px);
    position: absolute;
    left: 30px;
    top: 0px;
}
.eventFuncDialog-file{
    display: flex;
    flex: 1;
    line-height: 50px;
    height: 50px;
    margin-left: 85px;
    align-content: center;
}
.delMethod{
    color: #ff3d3d!important;
    margin-left: 20px;
    font-size: 20px;
    margin-top: 14px;
}
.openFormConfig-grid-head{
    display: flex;
    color: #555555;
    height: 40px;
    line-height: 40px;
    margin-left: 40px;
    div{
        flex: 1;
    }
}
.openFormConfig-grid-common{
    display: flex;
    height: 47px;
    align-items: center;
    border-bottom: 1px solid #dedede;
}
.openFormConfig-select{
    flex: 1;
    margin-right: 10px;
}

.openFormConfig-fixed{
    flex: 2;
    margin-right: 10px;
}

.openFormConfig-icon{
    width: 40px;
    text-align: center;
    font-size: 20px;
    cursor: pointer;
}
.openFormConfig-icon:hover{
    color: #1890ff;
}
.openFormConfig-add:hover{
    color: #1890ff;
}
.openFormConfig-add{
    margin-top: 15px;
    display: flex;
    cursor: pointer;
    i{
        font-size: 20px;
        margin-left: 10px;
        margin-right: 5px;

    }
}
</style>